package cn.ivicar.oss.guice;

import cn.com.carsmart.util.configmanagement.ConfigUtil;
import cn.com.carsmart.util.configmanagement.FileSystemConfigReaderImpl;
import cn.com.carsmart.ws.guice.BasicGuiceServletModule;
import cn.com.carsmart.ws.guice.GuiceConfig;
import cn.com.carsmart.ws.guice.MybatisDataBaseModule;
import cn.com.carsmart.ws.model.IvicarObjectSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import org.apache.log4j.xml.DOMConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import java.util.HashMap;
import java.util.Map;

public class OssGuiceConfig extends GuiceConfig {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(OssGuiceConfig.class);

	private static Injector injector = null;

	public OssGuiceConfig() {

	}

	public OssGuiceConfig(String environment) {
		this.environment = environment;
	}

	@Override
	public Injector getInjector() {

		if (injector == null) {
			String environment = this.getEnvironment();
			injector = getInjector(environment);
		}

		return injector;
	}

	public static Injector getStaticInjector() {
		return injector;
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		super.contextInitialized(servletContextEvent);

		try {
			String logconfig = ((FileSystemConfigReaderImpl) ConfigUtil.getConfigReader()).getBasePath() + "/log4j.xml";
			LOGGER.info("加载日志配置文件[{}]", logconfig);
			DOMConfigurator.configure(logconfig);
		} catch (Exception e) {
			LOGGER.warn("加载日志配置文件出错， 使用本地配置");
		}
	}

	public static Injector getInjector(final String environment) {
		Injector injector = Guice.createInjector(new MybatisDataBaseModule("ivicar", IvicarObjectSet.getSet()),
				new BasicGuiceServletModule() {
					protected void configureServlets() {
						super.configureServlets();
						Map<String, String> params = new HashMap<String, String>();
						params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "cn.ivicar.oss");
						serve("/ws/0.1/*").with(GuiceContainer.class, params);
					}
				});
		return injector;
	}

}
